<template>
  <page-header-wrapper :title="false">
    <a-card title="账户详情">
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="名称" :span="3">{{ detail.accName }}</a-descriptions-item>
        <a-descriptions-item label="类型" :span="3">{{ detail.accountType == 1?'已上账':'待上账' }}</a-descriptions-item>
        <a-descriptions-item label="初始余额" :span="3">{{ detail.startAmount }}元</a-descriptions-item>
      </a-descriptions>
    </a-card> 
    <a-card title="往来账信息" style="margin-top: 24px;">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="8">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="记账日期">
                <a-range-picker v-model="queryParam.date" />
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" @click="handleAdd(detail)">新增往来账</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :pagination="pagination"
        @change="handleTableChange"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="types" slot-scope="text, record">
          <template>
            {{ render(record.types) }}
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已审核</a-tag>
            <a-tag color="#abbac3" v-else>未审核</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleDetail(record)">详情</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <account-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      :accountType="this.detail.accountType"
      :supplyTypes="this.$route.query.types"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </page-header-wrapper>
</template>

<script>
import AccountForm from './AccountForm'
import moment from 'moment'
import { omit } from 'lodash-es'
import {getSuppliesAccountUsingPOST,getSuppliesAcclogListUsingGET ,addSuppliesAcclogUsingPOST} from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
export default {
  name: 'AgentAccountDetail',
  components: {
    AccountForm,
  },
  data() {
    return {
      queryParam: {
        pageNo:1,
        pageSize:10, 
        date: [ moment().startOf('months').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD') ],
        accId:this.$route.params.id,
      },
      advanced: false,
      mdll: null,
      mdl: null,
      pagination:{
        total: 0
      },
      visible: false,
      groupVisible: false,
      groupLoading: false,
      value: '',
      confirmLoading: false,
      detail:{},
      columns: [
        {
          title: '记账日期',
          dataIndex: 'date',
        },
        {
          title: '类型',
          dataIndex: 'types',
          needTotal: true,
          scopedSlots: { customRender: 'types' },
        },
        {
          title: '金额(元)',
          dataIndex: 'amount',
        },
        {
          title: '结余(元)',
          dataIndex: 'curAmount',
        },
        {
          title: '审核状态',
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '记账人',
          dataIndex: 'empName',
        },
        {
          title: '备注',
          dataIndex: 'memo',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loading:false,
      loadData: [],
    }
  },
  mounted(){
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    render(type) {
      switch (type) {
        case '1':
          return '采购入库'
        case '2':
          return '采购退库'
        case '3':
          return '保价'
        case '4':
          return '供应商回款'
        case '5':
          return '供应商退款'
        case '6':
          return '经销商收款'
        case '7':
          return '经销商退款'
        case '8':
          return '应收款'
        case '9':
          return '应付款'
      }
    },
    getDetail() {
      getSuppliesAccountUsingPOST({ id: this.$route.params.id })
        .then((res) => {
          this.detail = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch (val) {
      this.loading = true
      const params = {
        ...val,
        accId: this.$route.params.id,
        startTime: val?.date?.[0] ? moment(val?.date?.[0]).format('YYYY-MM-DD') : null,
        endTime: val?.date?.[1] ? moment(val?.date?.[1]).format('YYYY-MM-DD') : null,
      }
      // this.$route.params.id
      getSuppliesAcclogListUsingGET({ ...omit(params, ['date'])}).then((res) => {
        this.loadData = res.data.list
        this.loading = false
        this.queryParam.pageNo = this.pagination.current
        this.pagination = { ...this.pagination, total: Number(res.data.total) }
      })
      .catch((error) => {
        this.loading = false
        this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
      })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        queryCondition:this.queryParam.queryCondition,
        accId: this.$route.params.id,
        status:this.queryParam.status,
        date:this.queryParam.date,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
      })
    },
    handleDetail(record) {
      if(record.types == '4' ||record.types == '5' ||record.types == '6' ||record.types == '7' ||record.types == '8' ||record.types == '9' ){
        this.$router.push({ path: `/agent/order/${record?.orderId}`,query:{ types: this.$route.query.types  }  })
      }else if(record.types == '3'){
        this.$router.push({ path: `/purchasing/ProtectPriceRecord/${record?.orderId}` })
      }else if(record.types == '1' ){
        this.$router.push({ path: `/purchasing/inStoreRecord/detail/${record?.orderId}` })
      }else if(record.types == '2' ){
        this.$router.push({ path: `/purchasing/backstorerecord/detail/${record?.orderId}` })
      }
      // this.$router.push({ path: `/service/supplier/order/${record?.id}` })
    },
    handleAdd(detail) {
      this.mdl = {detail}
      this.visible = true
    },
    handleOk() {
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          addSuppliesAcclogUsingPOST({ ...values,accId:this.detail.id })
            .then(() => {
              this.handleSearch(this.queryParam)
              this.$message.success('操作成功')
              this.visible = false
              this.confirmLoading = false
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.confirmLoading = false
        }
      })

    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
